/*
 * Created on Feb 20, 2005
 */
package com.scalar.chiptrack.finance.openpo.actioncommands;

import java.util.ArrayList;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.scalar.chiptrack.actioncommands.ActionCommand;
import com.scalar.chiptrack.finance.openpo.dao.PurchaseOrderDAO;
import com.scalar.chiptrack.finance.openpo.forms.OpenPurchaseOrderForm;
import com.scalar.chiptrack.users.ErrorReport;
import com.scalar.chiptrack.utils.Logger;

/**
 * @author Ravikanth
**/
public class OpenPurchaseOrderAuditTrailCommand extends ActionCommand
{
	/*
	 * Shows Purchase Order Audit Trail
	 */
	public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		HashMap errors			= ( HashMap ) request.getAttribute( ERROR_MESSAGES );
		HashMap info            = ( HashMap ) request.getAttribute( INFO_MESSAGES );
		String actionForward 	= "auditTrail";
		String action   		= request.getParameter( REQUEST_ACTION );
		HttpSession mSession 	= request.getSession();
		OpenPurchaseOrderForm purchaseOrderForm = ( OpenPurchaseOrderForm ) form;
		ArrayList auditList 	= new ArrayList();

		try
		{
			if( action.equalsIgnoreCase( "auditTrail" ) )
			{

                if ( purchaseOrderForm == null )
                {
                    purchaseOrderForm = new OpenPurchaseOrderForm();
                    purchaseOrderForm.setPurchaseOrder_id( Integer.parseInt( request.getParameter("purchaseOrder_Id") ));
                }

				if( purchaseOrderForm.getPurchaseOrder_id() != -1 )
				{
					auditList = PurchaseOrderDAO.loadPOAuditTrail( purchaseOrderForm.getPurchaseOrder_id() );
					if( auditList == null )
					{
						auditList = new ArrayList();
					}
					else if( auditList.isEmpty() == true )
					{
						Logger.info( INFO_PURCHASE_ORDER_NO_AUDIT_TRAIL_INFO );
						info.put( INFO_PURCHASE_ORDER_NO_AUDIT_TRAIL_INFO, null );
					}
					request.setAttribute( "auditList", auditList );
				}
				else
				{
					Logger.error( ERROR_LOADING_OPEN_PURCHASE_ORDER_AUDIT_TRAIL );
					errors.put( ERROR_LOADING_OPEN_PURCHASE_ORDER_AUDIT_TRAIL, null );
				}
				actionForward 	= "auditTrail";
			}
		}
		catch ( Exception e )
		{
			Logger.error( ERROR_LOADING_OPEN_PURCHASE_ORDER_AUDIT_TRAIL, e );
			errors.put( ERROR_INTERNAL_SERVER_ERROR, ERROR_LOADING_OPEN_PURCHASE_ORDER_AUDIT_TRAIL );
			mSession.setAttribute( ERROR_REPORT_OBJECT, new ErrorReport( "Error while executing the command", e ) );
			actionForward = "auditTrail";
		}
		return mapping.findForward( actionForward );
	}
}
